package com.my.hotel.service;

import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.my.hotel.entity.Order;
import com.my.hotel.entity.serverPage.JdUser;
import com.my.hotel.entity.vo.Trade;
import com.my.hotel.mapper.OrderMapper;
import com.my.hotel.util.AlipayConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;

@Service
public class PayService {

    public void pay(Trade trade, HttpServletResponse response) throws Exception {

        //设置响应编码格式--------防止中文产生乱码
        response.setContentType("text/html;charset=utf-8");
        //产生输出流
        PrintWriter out = response.getWriter();


        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);

        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = trade.getTradeNo();
        //付款金额，必填
        String total_amount = trade.getTradePrice();
        //订单名称，必填
        String subject = trade.getTradeName();
        //商品描述，可空
        String body = trade.getTradeDetail();

        alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\","
                + "\"total_amount\":\"" + total_amount + "\","
                + "\"subject\":\"" + subject + "\","
                + "\"body\":\"" + body + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        //请求
        String result = alipayClient.pageExecute(alipayRequest).getBody();

        //输出
        out.println(result);
    }

    @Autowired
    OrderMapper orderMapper;
    public void addOrder(Trade t, String status, HttpSession session) throws ParseException {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        java.util.Date parse = format.parse(t.getDate());
        Date date = new Date();
        String format1 = format.format(date);
        JdUser userInfo = (JdUser) session.getAttribute("userInfo");
        Order order = new Order(0, t.getTradeNo(), status, format1, t.getDate(), Integer.parseInt(t.getDay()), userInfo.getId(), userInfo.getUsername(), t.getId(), Double.parseDouble(t.getTradePrice()));
        orderMapper.add(order);

    }

    public void update(String tradeNo) {
        orderMapper.changeStatusByNum(tradeNo);
    }
}
